<div class="main-container"> 
    <div style="display: flex; align-items: center; gap: 10px;"> 
	    <h3>网页国际语言信息列表 (International Language Tags for Web)</h3>
		<label style="line-height: 2em;"">搜索(Search)</label>
		<input style="height: 2em; padding: 0 5px; box-sizing: border-box;"  type="text"  list="input-suggestions" size="48"
		   onChange="search(this.value,'dataTable')" onClick="dClick(this,'a1')">
		</div>
		<datalist id="input-suggestions">
		</datalist>
  		
        <div class="table-scroll-container">  
          <div class="tables-container"> 
            <table id="dataTable" class="fixed-height-table">
                <thead id="tableHead">
                   <tr>
                       <th>编码</th>
                       <th>中文名</th>
                       <th>英文名</th> 
                       <th>所属洲</th> 
                       <th>语言</th> 
                   </tr>
               </thead>
               <tbody id="tableBody"> 
               </tbody>
            </table>     
         </div>
      </div>   
      <div class="button-container">
           <button class="btn btn-primary" id="rightAddBtn" onClick="newCountry()">新增国家/new country</button> 
           &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <button class="btn btn-primary" id="rightAddBtn" onClick="newArea()">新增地区/new area</button> 
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <button class="btn btn-warning" id="rightEditBtn" onClick="editItem()">编辑/edit</button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <button class="btn btn-danger" id="rightDeleteBtn" onClick="delItem()">删除/delete</button> 
      </div> 
      
      <div id="modal-window" class="modal"> 
      </div>
</div> 

<script id="popupTemplate" type="text/html"> 
	<div class="modal-content-{{rows}}">
       <h3 class="modal-title">{{title}}</h3>
            <table class="no-hover" border=0 width="90%" align="center" > 
                <input type="hidden" name="acode" value="">
                <tr>
                    <td width="25%" style="text-align: right;">
                     {{if dType==1 || dType==2}} 所属洲:{{/if}}
                     {{if dType==3 || dType==4}} 所属国:{{/if}}
                     </td>
                    <td width="75%">
                    <input type="text"  style="height:26px" name="scode" value="" size="24"
                     list="sa-suggestions"  id="saCode" {{if dType==1}} onclick = "dClick(this,'a2')" {{/if}}></td>
                     <datalist id="sa-suggestions">
		             </datalist>
                </tr>
                <tr>
                    <td width="25%" style="text-align: right;">中文名:</td>
                    <td width="75%"><input type="text" style="height:26px" name="cname" value="" size="36"></td>
                </tr>
                <tr>
                    <td width="25%" style="text-align: right;">英文名:</td>
                    <td width="75%"><input type="text" style="height:26px" name="ename" value="" size="64"></td>
                </tr> 
                <tr>
                    <td width="25%" style="text-align: right;">语言:</td>
                    <td width="75%"><input type="text" style="height:26px" name="lcode" value="" size="48"
                     list="slang-suggestions" onClick="dClick(this,'a3')"></td>
                     <datalist id="slang-suggestions">
		             </datalist>
                </tr>
            </table>
            <div class="modal-buttons">
                <button class="modal-btn cancel-btn" onclick="closeModalById('modal-window')">取消</button>
                <button class="modal-btn save-btn" onclick="saveItem({{dType}})">保存</button>
            </div>
        </div>
</script>

<script> 
    var langList = null;
    var continentList = null;
    var areaList = null; 
    var continentClickHandler = null;
    var currentCode = null;
  
    function updateAreaList(item){  
    	var list = areaList;  
    	var saved = false; 
    	
		for(var i=0;i<list.length;i++){
		    
			if(item["acode"] == list[i]["acode"]){
			    list[i] = item;
				saved = true;
				break;
			}else
			if(item["acode"] < list[i]["acode"]){
			    list.splice(i, 0, item);  //insert before 
				saved = true;
			    break;
			}else{
			  continue;
			}
		} 
		if(saved == false){
			list.push(item);
		} 
		closeModalById('modal-window'); 
    }
    
    
    /*
    *len 本级编号的长度
    *slen 上级编号的长度
    */
    function makeCode(scode , len , slen){
    	console.log("Make code, superLen:"+slen+"superCode:"+scode+",codeLen:"+len);
    	var list = areaList;
    	var mItem = null;
    	
		for(var i=0;i<list.length;i++){
			if(list[i]["acode"].length==len && list[i]["acode"].startsWith(scode) ){
				if(mItem == null){
					mItem = list[i];
				}else{
					var n = parseInt(list[i]["acode"].substring(slen)) - parseInt(mItem["acode"].substring(slen)); 
					if(n == 1){
						mItem = list[i];
					}else{
						break;
					}
				} 
			} 
		}
		var index = 1;
		if(mItem != null){
			index = parseInt(mItem["acode"].substring(slen)) + 1; 
		}
		var code = scode;
		if(index < 10){
			code = code +"0";
		}
		code = code + String(index);
		
    	return code;
    }
    
    function saveItem(type){
    	var item = {"acode":getInputValue("acode"),
    			"cname":getInputValue("cname"),
    			"ename":getInputValue("ename"),
    			"lcode":getInputValue("lcode"),
    			"scode":getInputValue("scode"),
    			}; 
    	
    	console.log("Input:"+JSON.stringify(item,null,2));
    	
    	if(item["cname"].length < 2 || item["cname"].length > 12){
    		alert("中文名称的字符数必须在2到12个之间\r\n"+
    				"Chinese name must between 2 and 12 chars");
    		return;
    	}
    	
    	if(item["ename"].length < 4 || item["ename"].length > 32){
    		alert("英文名称的字符数必须在4到32个之间\r\n"+
    		      "English name must between 4 and 32 chars");
    		return;
    	}
    	
    	if(item["lcode"].length < 1){
    		alert("语言代码不能为空\r\n"+
		      "You must input language code");
		    return;
    	}
    	
    	item["scode"] = fatchCode( item["scode"] ); 
    	item["lcode"] = fatchCode(item["lcode"]); 
    	item["continent"] = item["scode"].substring(0,1);
    	
    	if(type == 1 || type == 3){ //new country , or area 
    		if(type==1){
    			item["acode"] = makeCode( item["scode"] , 3, 1 ); 
    		}else{
    			item["acode"] = makeCode( item["scode"] , 5, 3 ); 
    		} 
    	} 
    	if(item["acode"].length==3){
    		item["isArea"] = 0;
    	}else{
    		item["isArea"] = 1;
    	}
    	
    	console.log(JSON.stringify(item,null,2));
    	
    	var url = area_save_uri ;
		var token = curUser["token"];
    	
    	ajaxPostJson(url , token, item , function(status,ret){
			  console.log("Status="+status);
			 // console.log("list Data="+JSON.stringify(ret,null,2)); 
			  if(status==0){
				  if(ret.status==1){   
					  var item = ret["data"];
					  updateAreaList(item);
					  showAreaList();
					  var row = findRowInTbaleBodyByColumnValue("dataTable",0,item["acode"]);
					  if(row>=0){
						  selectAndScrollToRow("dataTable",row+1);  //thead作为第一行
						  setCurrentCode(item["acode"]);
					  }
				  }else{
					  alert("Error:"+ret["errorCode"]+"\r\nMsg="+ret["desc"]);  
				  }
			  }else{
				  alert("httpStatus="+status+"\r\nErrorMsg="+ret);
			  } 
	    });   
    }
     
    
    function showItem(type,item){ 
    	 
    	if(type==1){ //国家
			setInputSuggestions("sa-suggestions",continentList,"code");  //设置洲可选列表 
		}else
		if(type==3){ //地区 
			var c = getItemFromList(areaList,"acode",item["scode"]); 
			setInputValue("scode",c["acode"]+"/"+c["cname"]+"/"+c["ename"]);
			var lan = getItemFromList(langList,"lcode",c["lcode"]); 
			setInputValue("lcode",lan["lcode"]+"/"+lan["cname"]+"/"+lan["ename"]);
		}else{
			if(type==2){ //国家 , 直接设置洲
				var c = getItemFromList(continentList,"code",item["scode"]); 
				setInputValue("scode",c["code"]+"/"+c["cname"]+"/"+c["ename"]);
    		}else
			if(type==4){ //地区,直接设置国家
				var c = getItemFromList(areaList,"acode",item["scode"]); 
				setInputValue("scode",c["acode"]+"/"+c["cname"]+"/"+c["ename"]);
    		}else{
    			alert("Invalid type");
    			return;
    		}
		}
    	setInputSuggestions("slang-suggestions",langList,"lcode");  //设置语言输入可选类别 
		var lan = getItemFromList(langList,"lcode",item["lcode"]); 
		
		if(type !=1 ){ //设置上级 地区（洲，国家） 为只读 ，
			 const input = document.getElementById('saCode');
			 input.readOnly = true;
		}
		setInputValue("acode",item["acode"]); 
		setInputValue("cname",item["cname"]);
		setInputValue("ename",item["ename"]);
		if(lan != null){
			setInputValue("lcode",lan["lcode"]+"/"+lan["cname"]+"/"+lan["ename"]);
		} 
    }
    
    
    function newCountryItem(){
    	var item = {"acode":"","scode":"","ename":"","cname":"","lcode":0};
    	return item;
    }
    
	function newAreaItem(country){
		var scode = country["acode"]; 
		if(scode.length>3){
			scode =scode.substring(0,3); //上级国家代码
		}
		var item = {"acode":"","scode":scode,"ename":"","cname":"","lcode":country["lcode"]};
    	return item;
    }
    
    function popWindow(type,item){
    
    	if(item==null){
    		return;
    	} 
    	var json={};
    	var title = ["新增国家(Add New Country)","编辑国家(Edit Country)",
    		"新增地区(Add New Area)","编辑地区(Edit Area)"];
    	json["rows"] = 5;
        json["dType"] = type;
        json["title"] = title[type-1];  
        
        var html = template("popupTemplate", json);    
        console.log(html);
    	document.getElementById("modal-window").innerHTML = html; 
    	openEditModalById("modal-window"); 
    	showItem(type,item);
    }
    
	function newCountry(){ 
		var item = newCountryItem();
		popWindow(1,item);
	}
	
	function newArea(){ 
		var country = getItemFromList(areaList,"acode",currentCode); 
		if(country == null){
			alert("Please select one country!");
			return;
		}
		var item = newAreaItem(country);
		popWindow(3,item);
	}
	
	function removeFromList(item){
		console.log("remove item="+JSON.stringify(item,null,2)); 
		var pos = -1;
		for(var i=0;i<areaList.length;i++){
			if(areaList[i]["acode"] == item["acode"]){
				pos = i;
				break;
			}
		}
		if(pos < 0){
			return;
		} 
		areaList.splice(pos,1);
		showAreaList();
	}
	
	function delItem(){
		if(currentCode == null){
			alert("Please select one country or area!");
			return;
		}
		var item = getItemFromList(areaList,"acode",currentCode); 
		if(item == null){
			alert("Please select one country or area!");
			return;
		}
		if(item["acode"].length == 3){
			if(haveChild(areaList , item["acode"])){
				alert("Can not delete country that have child area!");
				return;
			}
		}
		
		//alert("Are you sure to delete item , code:" + item["acode"] +"?");
		var url = area_del_uri ;
		var token = curUser["token"];
    	
    	ajaxPostJson(url , token, item , function(status,ret){
			  console.log("Status="+status);
			 // console.log("list Data="+JSON.stringify(ret,null,2)); 
			  if(status==0){
				  if(ret.status==1){   
					  removeFromList(ret["data"]);
				  }else{
					  alert("Error:"+ret["errorCode"]+"\r\nMsg="+ret["desc"]);  
				  }
			  }else{
				  alert("httpStatus="+status+"\r\nErrorMsg="+ret);
			  } 
	    }); 
	}
	
 
	function editItem(){  
		if(currentCode == null){
			alert("Please select one country or area!");
			return;
		}
		var item = getItemFromList(areaList,"acode",currentCode); 
		if(item == null){
			alert("Please select one country or area!");
			return;
		}
		var type = 2;
		if(item["acode"].length==3){
			type = 2;
			item["scode"] = item["acode"].substring(0,1); //设置上级地区代码，洲
		}else{
			type = 4;
			item["scode"] = item["acode"].substring(0,3); //设置上级地区代码，国家
		}
		popWindow(type,item);
	}
	 
	
	function showItemValue(item,who){
		console.log(JSON.stringify(item,null,2));
	}
	
	
	function setInputSuggestions(suggestId, list,codeName){
    	const body = document.getElementById(suggestId);
   		let html = '';
   	    for (let i = 0; i< list.length; i++) {  
   	    	var t = list[i];
   	    	html +="<option value='"+t[codeName]+"/"+t["cname"]+"/"+t["ename"]+"'>"; 
   	    }
   	    console.log("suggestion list:"+html);
   	    body.innerHTML = html ; 
    }  
	
	function haveChild(list , code){
		for(var i=0;i<list.length;i++){
			if(list[i]["acode"].startsWith(code) && list[i]["acode"].length > code.length ){
				return true;
			} 
		}
		return false;
	}
	
	function getItemFromList(list,cname,cvalue){
		for(var i=0;i<list.length;i++){
			if(list[i][cname] == cvalue){
				return list[i];
			} 
		}
		return null;
	}
	 
	function setCurrentCode(c){
    	currentCode = c; 
    }
	
	function getContent(code,isObj=false){
		var c = code.charAt(0);
		var list = continentList;
		for(let i=0;i<list.length;i++){
			var t = list[i];
			if(t["code"] == c ){
				if(isObj){
					return t;
				}
				return t["code"] +"/" + t["cname"] +"/" +t["ename"];
			} 
		}
		if(isObj){
			return null;
		}
		return "0/c/e";
	}
	
	function getLang(code,isObj=false){ 
		var list = langList;
		for(let i=0;i<list.length;i++){
			var t = list[i];
			if(t["lcode"] == code ){
				if(isObj){
					return t;
				}
				return t["lcode"] +"/" + t["cname"] +"/" +t["ename"];
			} 
		}
		if(isObj){
			return null;
		}
		return "null/c/e";
	} 
	
	function showAreaList(){ 
		const body = document.getElementById("tableBody"); 
		body.innerHTML="";
   		let html = '';
   		var list = areaList;
   	    for (let i = 0; i< list.length  ; i++) {  
   	    	var t = list[i]; 
   	        html += "<tr onClick=\"setCurrentCode('" + t["acode"] + "')\">"+  
   	           "<td>" + t["acode"] + "</td>"+
               "<td>" + t["cname"] + "</td>"+
               "<td>" + t["ename"] + "</td>"+ 
               "<td>" + getContent(t["acode"]) + "</td>"+ 
               "<td>" + getLang(t["lcode"]) + "</td>"+ 
   	           "</tr>"; 
   	    } 
   	   
   	    console.log(html);
   	    body.innerHTML = html ; 
   	    appendBlank("tableBody",7,5);  //table 有幽灵bug导致显示变形
   	    setupRowHighlight("tableBody");
   	    setSuggestions(list);  
	} 
	
	function setSuggestions(list){
    	const body = document.getElementById("input-suggestions");
   		let html = '';
   	    for (let i = 0; i< list.length; i++) {  
   	    	var t = list[i];
   	    	html +="<option value='"+t["acode"]+"/"+t["cname"]+"/"+t["ename"]+"'>"; 
   	    }
   	    body.innerHTML = html ; 
    }
	
	function readContinentList(){  
    	var url = "./json/continent.json?" + Date.now() ;  
    	ajaxGetJson(url,function(status,res){
    		if(status==0){ 
    			continentList = res["list"];
    			readLangList();
    		}else{
    			alert("Error!");
    		} 
    	}); 
    }
	
	function readLangList(){ 
		var url = lang_list_uri+"/"; 
		debugger;
		ajaxGetJson(url , function(status,ret){
			  console.log("Status="+status);
			 // console.log("list Data="+JSON.stringify(ret,null,2)); 
			  if(status==0){
				  if(ret.status==1){  
					  langList = ret["data"];      
					  readAreaList();
				  }else{
					  alert("Error:"+ret["errorCode"]+"\r\nMsg="+ret["desc"]);  
				  }
			  }else{
				  alert("httpStatus="+status+"\r\nErrorMsg="+ret);
			  } 
	    },true,null);
	}  
	
	function readAreaList(){
		var url = area_list_uri ; //+ "/0"; 
		debugger;
		ajaxGetJson(url , function(status,ret){
			 //console.log("Status="+status);
			 // console.log("list Data="+JSON.stringify(ret,null,2)); 
			  if(status==0){
				  if(ret.status==1){  
					  areaList = ret["data"];     
					  showAreaList();
				  }else{
					  alert("Error:"+ret["errorCode"]+"\r\nMsg="+ret["desc"]);  
				  }
			  }else{
				  alert("httpStatus="+status+"\r\nErrorMsg="+ret);
			  } 
	    },true,null);
	}
	
	readContinentList();  
    
</script>
